package main

import (
	"bytes"
	"encoding/xml"
	"fmt"
)

var xmlDoc = `
<?xml version="1.0" encoding="UTF-8"?>
<site>
  <name>RUNOOB</name>
  <url country="China">https://www.runoob.com</url>
  <logo>runoob-logo.png</logo>
  <desc>编程学习网站</desc>
</site>
`

func main() {
	data := bytes.NewBuffer([]byte(xmlDoc))
	decoder := xml.NewDecoder(data)
	var (
		t       xml.Token
		err     error
		inRange bool
	)
	for t, err = decoder.Token(); err == nil; t, err = decoder.Token() {
		switch token := t.(type) {
		case xml.StartElement:
			name := token.Name.Local
			fmt.Println("Start Element: ", name)
			if inRange {
				if name == "url" {
					var country string
					for _, attr := range token.Attr {
						if attr.Name.Local == "country" {
							country = attr.Value
						}
					}
					fmt.Printf("[Find url, country = %v]\n", country)
				}
			} else {
				if name == "site" {
					inRange = true
				}
			}
		case xml.EndElement:
			name := token.Name.Local
			fmt.Println("End Element: ", name)
			if inRange && name == "site" {
				inRange = false
			}
		case xml.CharData:
			content := string([]byte(token))
			fmt.Println("Char Data: ", content)
		default:
		}
	}
}
